<template>
  <!--  人员-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="机台编号">
          <el-input v-model="searchParam.machineCode" placeholder="请输入机台编号" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchParam.type" placeholder="请选择类型" clearable filterable
                     style="width: 200px" @change="typeChange">
            <el-option v-for="item in lightList" :key="item.value" :label="item.text" :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="详细类型">
          <el-select v-model="searchParam.issueType" placeholder="请选择详细类型" clearable filterable
                     style="width: 200px">
            <el-option v-for="item in lightDetailList" :key="item.label" :label="item.label" :value="item.label"/>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="用户昵称">-->
<!--          <el-input v-model="searchParam.nickname" placeholder="请输入用户昵称" clearable style="width: 200px"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="工厂/车间">-->
<!--          <el-tree-select v-model="searchParam.organizationId" :data="workOptions" check-strictly filterable-->
<!--                          :render-after-expand="false" :props="{-->
<!--    									children: 'children',-->
<!--    									label: 'orgName',-->
<!--    									value: 'id',-->
<!--    								}" style="width: 300px"/>-->
<!--        </el-form-item>-->

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <!--          <el-button :icon="Plus" @click="handleAdd()">新建</el-button>-->
        </div>
      </div>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="未完成" name="unfinished"></el-tab-pane>
        <el-tab-pane label="已完成" name="completed"></el-tab-pane>
      </el-tabs>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 380px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize
              + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="machineCode" label="机台" align="center" min-width="250"/>
        <el-table-column prop="type" label="类型" align="center" min-width="250"/>
        <!--				<el-table-column prop="organizationName" label="工厂/车间" align="center" min-width="250" />-->
        <el-table-column prop="issueType" label="详细类型" align="center" min-width="250"/>
        <!--				<el-table-column prop="userPersonName" label="人员姓名" align="center" min-width="250" />-->
        <el-table-column prop="keywords" label="问题关键词" align="center" min-width="200"/>
        <el-table-column prop="expectTime" label="期望解决日期" align="center" min-width="200"/>
        <el-table-column prop="sex" label="待处理人" align="center" min-width="200">
          <template #default="scope">
            <text v-for="(item,index) in scope.row.handerUserList" :key="index">
              {{ item.handlerName }}
              <text v-if="index <  scope.row.handerUserList.length - 1">、</text>
            </text>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="100" v-if="searchParam.status == 0">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" type="text" size="small" plain
                       icon="Select">完成
            </el-button>
            <!--            <el-button @click="handleChange(scope.row)" type="text" size="small" plain-->
            <!--                       :icon="Edit">修改密码-->
            <!--            </el-button>-->
            <!--            <el-button @click="handleDel(scope.row)" text type="danger" size="small"-->
            <!--                       :icon="Delete">删除-->
            <!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current"
                       v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100, 200, 500]"
                       layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="800">
      <el-form :model="formData" label-width="90px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">

          <el-col :span="12">
            <el-form-item required label="用户账号" prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户账号" clearable
                        style="width:300px "></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item required label="用户昵称" prop="nickname">
              <el-input v-model="formData.nickname" placeholder="请输入用户昵称" clearable
                        style="width:300px "></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item required label="性别" prop="sex">
              <el-select v-model="formData.sex" placeholder="性别" clearable filterable
                         style="width: 300px">
                <el-option key="0" label="男" :value="1"/>
                <el-option key="1" label="女" :value="2"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话">
              <el-input v-model="formData.phone" placeholder="请输入电话" clearable type="number"
                        maxlength="11" style="width:300px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input v-model="formData.email" placeholder="请输入邮箱" clearable
                        style="width:300px "></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色权限" required prop="roleId">
              <el-select v-model="formData.roleId" clearable filterable placeholder="请选择">
                <el-option v-for="item in roleData" :key="item.id" :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工厂/车间" required prop='organizationIds'>
              <el-tree-select
                  v-model="formData.organizationIds"
                  :data="workOptions"
                  :props="{
									children: 'children',
									label: 'orgName',
									value: 'id',
								}"
                  multiple
                  show-checkbox
                  node-key="id"
                  style="width: 680px"
              />
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {ref, reactive, computed, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useEquipmentData} from '@/hooks/baseData/equipment';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Search, Share, Upload, Refresh, Plus, DocumentCopy} from '@element-plus/icons-vue';


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const configTableShow = ref(false);

const handleClick = (e) => {
  console.log(e, 'handleClick');
};

const rowInfo = ref({});
const organizationOptions = ref([]);


const workOrderList = ref({});

const showMaterial = ref(false);

const workDetailData = ref([]);

const workOrderChange = (e) => {
  if (!e) {
    formData.count = null;
    return false;
  }
  axiosInstance.post('/api/workOrder/queryByWorkId', {id: e})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        formData.count = res.data.orderCount;
        formData.materialId = res.data.materialId;
        formData.productId = res.data.productId;
      });
};

const addWorkOrderDetail = () => {
  workDetailData.value.push({});
};


const delWorkOrderDetail = (e) => {
  workDetailData.value.splice(e, 1);
};


// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
  axiosInstance.put('/api/basedataQualityScheme/update', updatedRowInfo).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
    showConfig.value = false;
    showMaterial.value = false;
    // 刷新配置质检项列表
    getList();
  });
};


const pageTotal = ref(null);//页面总数
// const formData = reactive({});//form表单
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const activeTab = ref('unfinished'); // 默认选中"未完成"标签页
const searchParam = ref({
  status: 0 // 默认查询未完成状态
});

const showConfig = ref(false);
const configData = ref({});
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});//弹出层标题
import CryptoJS from 'crypto-js';
import type {ComponentSize, FormInstance, FormRules} from 'element-plus';
import {lineAll} from '@/api/baseData/productionLine';

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  name: string;
  code: string;
  qualityWay: string;
  proportionNumber: string;
  qualityNumber: string;
  qualityType: string;
  qualityInterval: number;
  qualityIsLive: boolean;
  qualityRemark: string;
  organizationId: string;
}


const initialFormData = {
  username: '',
  nickname: '',
  sex: null,
  phone: '',
  email: '',
  roleId: null,
  organizationIds: []
};

let formData = reactive<RuleForm>(initialFormData);


const rules = reactive<FormRules<formData>>({
  nickname: [
    {required: true, message: '请输入用户昵称', trigger: 'blur'}
  ],
  sex: [
    {required: true, message: '请选择性别', trigger: 'blur'}
  ],
  username: [
    {required: true, message: '请输入用户账号', trigger: 'blur'}
  ],
  roleId: [
    {required: true, message: '请选择角色权限', trigger: 'blur'}
  ],
  deptId: [
    {required: true, message: '请选择角色权限', trigger: 'blur'}
  ],
  organizationIds: [
    {required: true, message: '请选择工厂/车间', trigger: 'blur'}
  ],
  userPersonId: [
    {required: true, message: '请选择人员', trigger: 'blur'}
  ]
});


// const paginatedData = reactive([])//列表数据
const paginatedData = ref<RuleForm[]>([]);

const materiaList = ref([]);//物料表
const userList = ref([]);//人员
const workRoomList = ref([]);//车间
const procedureOrderList = ref([]);//工序订单
const roleData = ref([]);//工序订单
const deptData = ref([]);//工序订单
const personOptions = ref([]);//工序订单

const getOption = () => {
  axiosInstance.post('/api/basedataRole/getAll', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    roleData.value = res.data;
  });

  // axiosInstance.post('/api/userPerson/getAll', {}).then(res => {
  // 	if (res.code !== 200) {
  // 		ElMessage.error(res.message);
  // 		return false;
  // 	}
  // 	personOptions.value = res.data;
  // });
  //
  // axiosInstance.post('/api/basedataDept/getAll', {}).then(res => {
  // 	if (res.code !== 200) {
  // 		ElMessage.error(res.message);
  // 		return false;
  // 	}
  // 	deptData.value = res.data;
  // });


  axiosInstance.post('/api/basedataOrganization/getPage', {
    current: 1,
    pageSize: 100000
  })
      .then(res => {
        organizationOptions.value = [];
        for (const item of res.data.records) {
          if (item.level == 2) {
            organizationOptions.value.push(item);
          }
        }
      });


  listFetch();
};

const workOptions = ref([]);


// 标签页点击事件
const handleTabClick = (tab) => {
  searchParam.value.status = tab.index;
  pageSearch.value.current = 1; // 切换标签页时重置到第一页
  getList(); // 重新获取数据
};
// 获取列表数据
const listFetch = () => {
  workOptions.value = [];
  lineAll({current: 1, pageSize: 100000}).then((res) => {
    if (res.code === 200) {
      workOptions.value = buildTree(res.data.records.map((item) => {
        return {
          ...item.extension,
          ...item
        };
      }));
      console.log(workOptions.value, 'workOptions');
    }
  });
};

// 构建树形结构
const buildTree = (items) => {
  const itemMap = {};
  const rootItems = [];
  items.forEach((item) => {
    itemMap[item.id] = {...item, name: item.orgName, children: []};
  });
  items.forEach((item) => {
    if (!item.parentId || item.parentId === '0') {
      rootItems.push(itemMap[item.id]);
    } else {
      if (itemMap[item.parentId]) {
        itemMap[item.parentId].children.push(itemMap[item.id]);
      }
    }
  });

  return rootItems;
};


// 获取列表接口
const getList = () => {
  axiosInstance
      .post('/api/andonCallRecord/getPage', {
        ...searchParam.value,
        ...pageSearch.value,
      })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};


// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {
    status: searchParam.value.status // 保留当前的status状态
  };
  pageSearch.value.current = 1;
  getList();
};

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  // ruleFormRef.value.resetFields()
  formData = reactive({});
  showCrud.value = true;
};

const handleEdit = (row: any) => {
  ElMessageBox.confirm('确定完成该条信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const param = {...row}
    param.status = 1
    axiosInstance.put(`/api/andonCallRecord/update`,
        param
    ).then(res => {
      ElMessage.success('操作成功');
      getList(); // 刷新数据
    });


  });
};
const lightDetailList = ref([])

const typeChange = (e) =>{
  searchParam.value.issueType = null
  lightDetailList.value = lightList.value.find(item => item.value === e).loop
}

const lightList = ref([{
  text: 'PASS-质检放行',
  value: 'PASS-质检放行',
  loop: [{
    label: '质检放行'
  }]
}, {
  text: 'U004-物料',
  value: 'U004-物料',
  loop: [{
    label: '材料质量问题'
  }, {
    label: '材料物资缺料'
  }]
}, {
  text: 'U003-设备',
  value: 'U003-设备',
  loop: [{
    label: '设备FAC1(设备故障)'
  },
    {
      label: '设备FAC2(设备故障)'
    },
    {
      label: '设备自动化(设备故障)'
    },
    {
      label: '缺刀具或配送错误'
    },
    {
      label: '缺模具或配送错误'
    },
    {
      label: '缺工装或配送错误'
    }
  ]
}, {
  text: 'U002-测量',
  value: 'U002-测量',
  loop: [{
    label: '待检结果超半个小时'
  }, {
    label: '首检多次不合格（含三次）'
  }]
}, {
  text: 'U001-人员',
  value: 'U001-人员',
  loop: [{
    label: '缺人或技能不符'
  }]
}, {
  text: 'U006-标准',
  value: 'U006-标准',
  loop: [{
    label: '生产作业文件不符或缺失'
  }]
}, {
  text: 'U005-安全',
  value: 'U005-安全',
  loop: [{
    label: '与作业安全不符'
  }]
}]);

const handleChange = (e) => {
  ElMessageBox.prompt('请输入新密码', '修改密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValidator: (value) => {
      // 密码长度验证
      if (value.length < 6) {
        return '密码长度不能少于6位';
      }

      if (value === 'Lg@pames2025!') {
        return '密码不能为默认密码';
      }

      // 包含英文大小写字母验证
      if (!/[a-z]/.test(value)) {
        return '密码必须包含英文字母';
      }
      // 包含阿拉伯数字验证
      if (!/[0-9]/.test(value)) {
        return '密码必须包含阿拉伯数字';
      }

      // 数字不允许连续三位以上验证
      if (/(012|123|234|345|456|567|678|789|890)/.test(value)) {
        return '数字不允许连续三位以上';
      }
      // 包含特殊字符验证

      return true;
    },
    inputErrorMessage: '密码不符合要求'
  })
      .then(({value}) => {
        axiosInstance.post(`/api/basedataUser/updatePassword`, {
          id: e.id,
          password: value
        }).then(res => {
          ElMessage.success('密码修改成功');
          getList(); // 刷新数据
        });
      });
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/basedataUser/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      getList(); // 刷新数据
    });


  });
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      // formData.userPersonName = personOptions.value.find(item => item.id == formData.userPersonId).userName;
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/basedataUser/update', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      } else {
        // formData.teamUserDTOS = {
        // 	userId: formData.teamUser
        // };
        // 新建
        // 				formData.deptId = 1;
        formData.password = CryptoJS.MD5('Lg@pames2025!').toString();

        axiosInstance.post('/api/basedataUser/save', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      }

    }
  });
};


onMounted(() => {
  getList();
  getOption();
});

</script>
<style scoped></style>
